﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc.UI.Layout;
using Volo.Abp.UI.Navigation;

namespace Volo.Abp.AspNetCore.Mvc.UI.Theme.Lepton.Themes.Lepton.Components.MainMenu
{
    public class MainMenuViewComponent : LeptonViewComponentBase
	{
		protected IMenuManager MenuManager { get; }

		protected IPageLayout PageLayout { get; }

		public MainMenuViewComponent(IMenuManager menuManager, IPageLayout pageLayout)
		{
			this.MenuManager = menuManager;
			this.PageLayout = pageLayout;
		}

		public async Task<IViewComponentResult> InvokeAsync()
		{
			var applicationMenu = await this.MenuManager.GetAsync("Main");
			var menuViewModel = base.ObjectMapper.Map<ApplicationMenu, MenuViewModel>(applicationMenu);
			if (!AbpStringExtensions.IsNullOrEmpty(this.PageLayout.Content.MenuItemName))
			{
				this.SetActiveMenuItems(menuViewModel.Items, this.PageLayout.Content.MenuItemName);
			}
			return base.View<MenuViewModel>("~/Themes/Lepton/Components/MainMenu/Default.cshtml", menuViewModel);
		}

		protected virtual bool SetActiveMenuItems(IList<MenuItemViewModel> items, string activeMenuItemName)
		{
			foreach (MenuItemViewModel menuItemViewModel in items)
			{
				if (menuItemViewModel.MenuItem.Name == activeMenuItemName || this.SetActiveMenuItems(menuItemViewModel.Items, activeMenuItemName))
				{
					menuItemViewModel.IsActive = true;
					return true;
				}
			}
			return false;
		}
	}
}
